package com.luxk.dbt;

import java.util.ArrayList;

public class WorkThread4Perf implements Runnable {
	
	protected byte lock[] = new byte[0];
	
	protected String name = null;
	protected MainContext mCtx = null;
	protected int thrId = 0;
	protected ArrayList<ExecIF> children = null;
	protected Thread thread = null;
	protected int duration = 0; // sec
	protected int repeat = -1;
	protected boolean isStarted = false;
	
	public WorkThread4Perf(String name, MainContext mCtx) {
		this.name = name;
		this.mCtx = mCtx;
	}
	
	public void setThrId(int val) {
		this.thrId = val;
	}
	
	public void setExec(ArrayList<ExecIF> children) {
		this.children = children;
	}
	
	public void setDuration(int val) {
		this.duration = val;
	}
	
	public void setRepeat(int val) {
		this.repeat = val;
	}
	
	public void start() {
		this.isStarted = true;
		this.thread = new Thread(this);
		this.thread.start();
		
	}
	
	public void start(int duration) {
		this.duration = duration;
		start();
	}
	
	public void stop() {
		this.isStarted = false;
		this.thread = null;
	}
	
	public boolean isFinished() {
		return !this.isStarted;
	}
		
	public void waitForSync(long millisec) {

		// wait for 
		if (millisec <= 0) {
			synchronized(this.lock) {
				try {
					this.lock.wait();
				} catch(InterruptedException e) {
					// do nothing
				}
			}
			
		} else {
			synchronized(this.lock) {
				try {
					this.lock.wait(millisec);
				} catch(InterruptedException e) {
					// do nothing
				}
			}
		}
	}

	public void awake() {
		this.lock.notifyAll();
	}
	
	public void run() {
		long startTime = System.currentTimeMillis();

		if(this.mCtx.isDebug())
			this.mCtx.writeDebug("WorkThread " + this.name + 
					"(#" + this.thrId + ") started");

		do {
			if(!this.mCtx.isStarted())
				break;
			
			for(ExecIF e: this.children)
				try {
					e.run();
				} catch(DBTException ee) {
					this.mCtx.writeError(ee);
				}
		} while(System.currentTimeMillis() - startTime < this.duration * 1000);
		
		this.isStarted = false;
		
		if(this.mCtx.isDebug())
			this.mCtx.writeDebug("WorkThread " + this.name + 
					"(#" + this.thrId + ") finished");
	}
}
